import Taro from "@tarojs/taro";
import axios from "axios";

function createHttp() {
  const client = axios.create({
    timeout: 1000 * 60 * 2,
    baseURL: 'https://modelhub-test.datagrand.com/'
  });

  // TODO: 其实就是为了把token加到header中去
  client.interceptors.request.use((config) => {
    Taro.showLoading({ title: '加载中' });
    // const token = $storage.token;

    // if (token) {
    //   conf.headers = {
    //     ...conf.headers,
    //     Authorization: `Bearer ${token}`
    //   };
    // }
    // return conf;
    return config;
  })

  client.interceptors.response.use(
    (response) => {
      const { data = {}, config = {} } = response;
      const { url, method } = config as any;
      const { status, message } = data;
      Taro.hideLoading();
      if (status !== 200) {
        const _res = {
          url,
          method,
          status,
          message
        };
        // 注意：这里不能用是因为atMessage是taro-ui的接口，所以不能使用
        // Taro.atMessage({ type: 'error', message });
        return Promise.reject(_res);
      }
      return response;
    },
    (error) => {
      Taro.hideLoading();
      return Promise.reject(error);
    }
  );
  return client;
}

export const httpService = createHttp();